/**************************************************************************
File:        batchprocessor.cpp
Description:

Copyright:   (C) 2001 by ZJ Laczik
Email:       Zsolt.Laczik@eng.ox.ac.uk
****************************************************************************
Change log:
   begin      Mon Mar 19 2001
   15/2/2012	QT4 update
***************************************************************************/

#include <stdlib.h>
#include <stdio.h>
#include <dlfcn.h>
#include <unistd.h>

#include <QApplication>

#include "batchprocessor.h"

BatchProcessor * pBP;

void (* pbf)();
bool StopFlag;

void move_x_to(float pos) {
    pBP->MoveXTo(pos);
}
void move_y_to(float pos) {
    pBP->MoveYTo(pos);
}
void move_z_to(float pos) {
    pBP->MoveZTo(pos);
}
void move_to(float x, float y, float z) {
    pBP->MoveTo(x,y,z);
}
void fire() {
    pBP->Fire();
}
void burst() {
    pBP->Burst();
}
bool stop() {
    qApp->processEvents();
    return StopFlag;
}

BatchProcessor::BatchProcessor(QWidget *parent) : QObject(parent) {
    pBP = this;
    pbf = NULL;
    batchfn_lib_handle = NULL;
    StopFlag = false;
}

BatchProcessor::~BatchProcessor() {
}

void BatchProcessor::Run() {
    QString str;

    emit( Running(true) );

    str.sprintf("Batch: Starting");
    emit( StatusMsg(str, true) );

    if (pbf != NULL)
        (*pbf)();
    else {
        str.sprintf("Batch: Routine undefined");
        emit( StatusMsg(str, true) );
    }

    if (StopFlag) {
        str.sprintf("Batch: Stopped");
        emit( StatusMsg(str, true) );
        StopFlag = false;
    }
    else {
        str.sprintf("Batch: Finished");
        emit( StatusMsg(str, true) );
    }

    emit( Running(false) );
}

void BatchProcessor::Stop() {
    StopFlag = true;
}

void BatchProcessor::NewBatchFnDefined(const char * fn) {
    QString s;
    // load function library
    if (batchfn_lib_handle)
        dlclose(batchfn_lib_handle);

    mBatchFnLibName = fn;

    if (mBatchFnLibName == QString("<InvalidLibrary>")) {
        batchfn_lib_handle = NULL;
        pbf = NULL;
        return;
    }

    batchfn_lib_handle = dlopen( mBatchFnLibName.toUtf8().constData(), RTLD_NOW);
    if (!batchfn_lib_handle) {
        s.sprintf( "Batch: Library error - %s", dlerror() );
        emit( StatusMsg( s, true ) );
        pbf = NULL;
        return;
    }
    // get function from library
    // N.B. use mangled name: _Z5 + function + v
    pbf = ( void (*)() ) dlsym(batchfn_lib_handle, "_Z5batchv");
    if (pbf) {
        emit( StatusMsg("Batch: Routine loaded OK", true) );
    }
    else {
        emit( StatusMsg("Batch: Routine load failed", true) );
    };
}
